import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

// 是否显示重新登录
export const isRelogin = { show: false }

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const STORAGE_PRINTER_KEY = 'printer'
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_PRINT_API,
  // withCredentials: true, // send cookies when cross-domain requests
  headers: {
    authorization: 'Basic ' + btoa('ru:DDgYhQ9Dyx5gXT0CNRoF2AURyeXrmjA1')
  },
  timeout: 40000 // request timeout
})

const errorHandler = (error) => {
  let { message } = error
  if (message === 'Network Error') {
    message = '后端接口连接异常'
  } else if (message.includes('timeout')) {
    message = '系统接口请求超时'
  } else if (message.includes('Request failed with status code')) {
    message = '系统接口' + message.substr(message.length - 3) + '异常'
  }
  Message({ message: message, type: 'error', duration: 5 * 1000 })
  return Promise.reject(error)
}

request.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      const url = config.url.replace(process.env.VUE_APP_API_BASE_URL_PRINT, '')
      if (!store.getters.buttons.includes(url)) {
        // const error = new Error('无权限访问URL ' + url);
        // return Promise.reject(error);
      }
    }
    return config
  },
  (error) => {
    Message.error({ message: error })
  }
)
// 响应拦截器
request.interceptors.response.use(null, errorHandler)

export const getPrinter = (success, fail) => {
  request.get('/status/printers').then((res) => {
    if (res.status === 200) {
      success(res)
    } else {
      fail(res)
    }
  })
}

export const printUrl = async(url, success, fail, failPrinter) => {
  const printerCode = localStorage.getItem(STORAGE_PRINTER_KEY) || 1
  if (printerCode === null) {
    failPrinter()
    return
  }
  request({
    url: '/push/url',
    method: 'post',
    params: {
      printerCode: printerCode,
      url: url
    }
  })
    .then((res) => {
      if (res.status === 200) {
        if (res.data.status === 'error') {
          fail(res['data']['message'])
        } else {
          success(res)
        }
      } else {
        fail(res['data']['message'])
      }
    })
}

export const printFile = async(file, success, fail, failPrinter) => {
  const printerCode = localStorage.getItem(STORAGE_PRINTER_KEY) || 1
  if (printerCode === null) {
    failPrinter()
    return
  }
  const fd = new FormData();
  // fd.append('printerCode', 1)
  fd.append('file', file);
  console.log(file);
  request({
    url: '/push/file',
    method: 'post',
    params: {
      printerCode: printerCode,
    },
    data: fd
  })
    .then((res) => {
      if (res.status === 200) {
        if (res.data.status === 'error') {
          fail(res['data']['message'])
        } else {
          success(res)
        }
      } else {
        fail(res['data']['message'])
      }
    })
}
